// pages/statement/statement.js
let app = getApp()
let request = require('../../utils/request')
import * as echarts from '../../components/ec-canvas/echarts';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    barHeight: wx.getMenuButtonBoundingClientRect().bottom,
    pageAllHeight: app.globalData.pageAllHeight,
    pageHeight: app.globalData.pageHeight,
    parkId: 0,
    tabIndex: 1,
    dataTypeList: [1, 2, 3, 4, 5],
    parkPayMoney: 0,
    monthPayMoney: 0,
    subscribePayMoney: 0,
    todayIncomeFromShop: 0,
    LinkIndexMax: 0,
    LinkIndexMin: 0,
    ecLine: {
      lazyLoad: true,
      // 初始化图表
      onInit: function (canvas, width, height) {
        console.log('收益环比渲染ec');
        //初始化echarts元素，绑定到全局变量，方便更改数据
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        return chart;
      }
    },
    //  总收益占比分析
    ecMonthOnMonth: {
      lazyLoad: true,
      // 初始化图表
      onInit: (canvas, width, height)=> {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        this.chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(this.chart);
        return chart;
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ parkId: wx.getStorageSync('parkInfo').parkId })
    this.getPayInfo() //  缴费记录
    this.getMonthOnMonth()  //  环比分析
    this.getProportion()  //  占比分析
  },
  onReady: function () {

  },
  /**
   * 切换bar
   */
  selectBar(e) {
    let index = e.currentTarget.dataset.index
    let tabIndex = this.data.tabIndex
    if (tabIndex == index) {
      return
    }
    this.setData({ tabIndex: index })
    this.getPayInfo() //  缴费记录
  },
    /**
   * 额外收入
   */
  getParkExtraRevenue(){
    request.http('/order/orderInfo/getParkExtraRevenue', 'GET', { parkId: this.data.parkId, dateType: this.data.tabIndex })
      .then(res => {
        console.log('额外收入：', res)
        let data = res.data
        if (data.code == 200) {
          this.setData({
            todayIncomeFromShop: data.data
          })
        }
      })
  },
  /**
   * 获取缴费记录
   */
  getPayInfo() {
    this.getParkPay()
    this.getMonthPay()
    this.getSubscribePay()
    this.getParkExtraRevenue()
  },
  /**
   * 获取泊车缴费
   */
  getParkPay() {
    let that = this
    let dateType = this.data.tabIndex
    let url = '/order/orderInfo/getOrderRevenue'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            parkPayMoney: data.data
          })
        }
      })
  },
  /**
   * 获取月租缴费
   */
  getMonthPay() {
    let that = this
    let dateType = this.data.tabIndex
    let url = '/order/orderInfo/getMonthRevenue'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            monthPayMoney: data.data
          })
        }
      })
  },
  /**
   * 获取预约缴费
   */
  getSubscribePay() {
    let that = this
    let dateType = this.data.dataTypeList[this.data.tabIndex]
    let url = '/order-reserve/park-reserve-record/get-reserve-amount-by-date'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            subscribePayMoney: data.data
          })
        }
      })
  },
  /**
   * 总收益环比分析
   */
  getMonthOnMonth() {
    request.http(
      '/order/orderInfo/get-month-income', 
      'GET', 
      { parkId: this.data.parkId }
    ).then(res => {
        let data = res.data
        if (data.code == 200) {
          let earnings = data.data
          var earningArr = []
          for (var i = 0; i < earnings.length; i++) {
            earningArr.push([earnings[i], i+1])
          }
          earningArr.sort(function (a, b) {
            return a[0] - b[0]
          })
          this.setData({
            LinkIndexMax: earningArr[earningArr.length - 1],
            LinkIndexMin: earningArr[0]
          })
          // 重置柱状图
          this.mychartEcLine = this.selectComponent('#mychart-ecLine')  
          this.mychartEcLine.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            // ec渲染初始化图表之后再来这里去调取数据挂载上去
            setTimeout(() => {
              //  设置总收益环比分析参数
              setMonthOnMonthOption(chart, earnings);
              // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
              this.chart = chart;
              // 注意这里一定要返回 chart 实例，否则会影响事件处理等
              return chart;
             }, 200)  
          });
        }
      })
  },
  /**
   * 总收益占比分析
   */
  getProportion() {
    request.http(
      '/order/orderInfo/income',
      'GET', 
      { parkId: this.data.parkId }
    ).then(res => {
      console.log('总收益占比分析：', res)
      let data = res.data
      if (data.code == 200) {
        let earnings = data.data
        var xData = []
        xData.push(earnings.parkIncome)
        xData.push(earnings.monthIncome)
        xData.push(earnings.reserveIncome)
        xData.push(earnings.parkYearIncome)

        this.mychartEcdoughnut = this.selectComponent('#month-on-month-pie')  //  总收益占比分析
        this.mychartEcdoughnut.init((canvas, width, height, dpr) => {
          // 获取组件的 canvas、width、height 后的回调函数
          // 在这里初始化图表
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr // new
          });

          // ec渲染初始化图表之后再来这里去调取数据挂载上去
          setTimeout(() => {
            //  设置总收益占比分析参数
            setProportionOption(chart, xData);
            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
          }, 200)        
        });
      }
    })
  },
    /**
   * 返回
   */
  back: function() {
    wx.navigateBack({ delta: 1 })
  }
})
/**
 * 设置总收益环比分析参数
 */
function setMonthOnMonthOption(chart, xData) {
  var option = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '0',
      right: '0',
      bottom: '0',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      { type: 'value' }
    ],
    series: [
      {
        itemStyle: {
          // normal是柱状图的正常样式
          normal: {
            barBorderRadius: [30, 30, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [
              {
                offset: 1,
                color: '#5273F7'
              },
              {
                offset: 1,
                color: '#859DFF'
              }
            ]
            ),
          },
          // 移入当前的柱状图时改变颜色
          emphasis: {
            color: '#5273F7',
          }
        },
        type: 'bar',
        barWidth: '60%',
        data: xData
      }
    ]
  };
  console.log('总收益环比分析：', option)
  chart.setOption(option);
}

/**
 * 设置总收益占比分析参数
 */
function setProportionOption(chart, xData) {
  var option = {
    // tooltip: {
    //   trigger: 'item',
    // },
    backgroundColor: "#ffffff",
    series: [
      {
        // name: '总收益占比分析',
        label: {
          normal: { fontSize: 14 }
        },
        type: 'pie',
        center: ['50%', '50%'],
        radius: ['30%', '50%'],
        emphasis: {
          label: { show: true, fontSize: '14', fontWeight: 'bold' }
        },
        labelLine: { show: false },
        label: {
          normal: { formatter: '{b}\n{d}%', lineHeight: 18 }
        },
        data: [
          { name: '泊车费', value: xData[0], itemStyle: { color: '#2381FD' } },
          { name: '月租费', value: xData[1], itemStyle: { color: '#F8763B' } },
          { name: '预约费', value: xData[2], itemStyle: { color: '#33D4C1' } },
          { name: '红利收入', value: xData[3], itemStyle: { color: '#740ed4' } }
        ]
      }
    ]
  };
  chart.setOption(option);
}